<?php
class CommonAction extends Action {

    //默认新增ID
    protected $list = 0;

    function _initialize() {
         ini_alter("session.gc_maxlifetime", 28800);//会话时间延长到8小时
        if(!file_exists(DATA_PATH.'~config.php')) {
            $config = M("Configure");
            $list = $config->getField('var_name,value');
            // 所有配置参数统一为大写
            $tmp = array();
            foreach($list as $key=>$value) {
                if(0 === strpos($value,'array(')) {
                    $str = '$tmp[$key]='.$value.';';
                    eval($str);
                }else {
                    $tmp[$key] = $value;
                }
            }
            $content =   "<?php\nreturn ".var_export(array_change_key_case($tmp,CASE_UPPER),true).";\n?>";
            if(!file_put_contents(DATA_PATH.'~config.php',$content)) {
                $this->error('配置缓存失败！');
            }
        }
        C(include_once DATA_PATH.'~config.php');
        // 用户权限检查
        if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
            import ( '@.ORG.RBAC' );
            if (! RBAC::AccessDecision ()) {
                //检查认证识别号
                if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
                    //跳转到认证网关
                    redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
                }
                // 没有权限 抛出错误
                if (C ( 'RBAC_ERROR_PAGE' )) {
                    // 定义权限错误页面
                    redirect ( C ( 'RBAC_ERROR_PAGE' ) );
                } else {
                    if (C ( 'GUEST_AUTH_ON' )) {
                        $this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
                    }
                    // 提示错误信息
                    $this->error ( L ( '_VALID_ACCESS_' ) );
                }
            }
        }

		$mod_name = $this->getActionName();
        $this->assign('menuName',strtolower($mod_name));
        A('Public')->header();
    }
    public function index($name='') {
        //列表过滤器，生成查询Map对象
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        if(empty($name))
            $name=$this->getActionName();
        
        $model = D ($name);
        if (! empty ( $model )) {
            $this->_list ( $model, $map );
        }
        $this->display ();
        return;
    }

    //专用于搜索过滤页，选择返回结果
    public function search(){
        $this->index();
    }

    /**
     +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作
     * 可以在action控制器中重载
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    function getReturnUrl() {
        return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
        //return $_SERVER['HTTP_REFERER'];
    }

    function _before_index(){
        $this->assign('useAjax', 1);
    }

    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param string $name 数据对象名称
     +----------------------------------------------------------
     * @return HashMap
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _search($name = '') {
        //生成查询条件
        if (empty ( $name )) {
            $name = $this->getActionName();
        }
        //$name=$this->getActionName();
        $model = D ( $name );
        $map = array ();
        foreach ( $model->getDbFields () as $key => $val ) {
            if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
                $map [$val] = $_REQUEST [$val];
            }
        }
        return $map;

    }

    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
     * @param boolean $isGroup 是否过滤重复数据 mike add
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false,$isGroup=false) {
        //排序字段 默认为主键名
        if (isset ( $_REQUEST ['_order'] )) {
            $order = $_REQUEST ['_order'];
        } else {
            $order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
        }
        $pk = $model->getPk ();
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset ( $_REQUEST ['_sort'] )) {
            $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        if($isGroup)
            $count = $model->where ( $map )->count ('distinct '.$pk);
        else
            $count = $model->where ( $map )->count ($pk);
        if ($count > 0) {
            import ( "@.ORG.Page" );
            //创建分页对象
            if (! empty ( $_REQUEST ['listRows'] )) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = 15;//默认每页 显示15个
            }
            $p = new Page ( $count, $listRows );
            //分页查询数据
            if($isGroup)
                $voList = $model->where($map)->group($pk)->order(  $order . " " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
            else
                $voList = $model->where($map)->order(  $order . " " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            foreach ( $map as $key => $val ) {
                if (! is_array ( $val )) {
                    if($key == '_string' || strpos($key, '.') )  //去掉_string类或类似Order.key复杂查询
                        continue;
                    $p->parameter .= "&$key=" . urlencode ( $val ) . "&";
                }
            }
            //分页显示
            $page = $p->show ();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            //模板赋值显示
            $this->assign ( 'list', $voList );
            $this->assign ( 'sort', $sort );
            $this->assign ( 'order', $order );
            $this->assign ( 'sortImg', $sortImg );
            $this->assign ( 'sortType', $sortAlt );
            $this->assign ( "page", '<form method="get" action="" class="form-inline form-horizontal">第<input type="text" style="width:25px" name="p" value="'.$_REQUEST['p'].'">页<input type=submit value="GO" style="margin-right:5px;">'.$page.'</form>' );
        }
        Cookie::set ( '_currentUrl_', __SELF__ );
        return;
    }

    /**
     * 插入同时，记录相应的日志
     * @param <string> $filed  记录的字段名称，默认为name
     */
    function insert($jumpUrl='',$field='name') {
        $jumpUrl = empty($jumpUrl) ? $_REQUEST['jumpUrl'] : $jumpUrl ;

        //B('FilterString');
        $name=$this->getActionName();
        $model = D ($name);
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
             $mod_field = getModelName ($list, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '新增 '.$name.': '.$mod_field.' (编号：'.$list.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'新增',$name,$list);
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl',  $jumpUrl);
            $this->success ('新增成功!');
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
    }

    /**
     * 插入，但不返回提示，适用于批量操作。
     *插入同时，记录相应的日志
     * @param <string> $filed  记录的字段名称，默认为name
     */
    function micro_insert($field='name') {
        //B('FilterString');
        $name=$this->getActionName();
        $model = D ($name);
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
             $mod_field = getModelName ($list, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '新增 '.$name.': '.$mod_field.' (编号：'.$list.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'新增',$name,$list);
           
        } else {
            //失败提示
            Log::write('新增'.$name.'失败');
            //$this->error ('新增失败!');
        }
    }

    public function add() {
        $this->display ();
    }

    function read() {
        $this->edit ();
    }

    function edit() {
        $name=$this->getActionName();
        $model = M ( $name );
        $id = $_REQUEST [$model->getPk ()];
        $vo = $model->getById ( $id );
        $this->assign ( 'vo', $vo );
        $this->display ();
    }

    function update($field='name') {
        //B('FilterString');
        $name=$this->getActionName();
        $model = D ( $name );
        $id = intval($_POST['id']);
        $old = $model->where('id = '.$id)->find();
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            $new = $model->where('id = '.$id)->find();
            $mod_field = getModelName ($id, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
            //成功提示
            $jumpUrl = $_REQUEST['jumpUrl'];
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this->success ('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }
    }

     //更新，但不返回提示，适用于批量更新
    function micro_update($field='name') {
        //B('FilterString');
        $name=$this->getActionName();
        $model = D ( $name );
        $id = intval($_POST['id']);
        $old = $model->where('id = '.$id)->find();
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            $new = $model->where('id = '.$id)->find();
            $mod_field = getModelName ($id, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
            
        } else {
            //错误提示
            Log::write('编辑'.$name.'失败');
            //$this->error ('编辑失败!');
        }
    }

    /**
     +----------------------------------------------------------
     * 默认删除操作
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    public function delete() {
        //删除指定记录
        $name=$this->getActionName();
        $model = M ($name);
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $id = $_REQUEST [$pk];
            if (isset ( $id )) {
                $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
                $list=$model->where ( $condition )->setField ( 'status', - 1 );
                if ($list!==false) {
                    $jumpUrl = $_REQUEST['jumpUrl'];
                if(empty($jumpUrl))
                    $jumpUrl = Cookie::get ( '_currentUrl_' );
                $this->assign ( 'jumpUrl', $jumpUrl );
                    $this->success ('删除成功！' );
                } else {
                    $this->error ('删除失败！');
                }
            } else {
                $this->error ( '非法操作' );
            }
        }
    }
    public function foreverdelete($field='name') {
        //删除指定记录
        $name=$this->getActionName();
        $model = D ($name);
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $id = $_REQUEST [$pk];
            if (isset ( $id )) {
                $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
                $old = $model->where($condition)->findAll();
                $mod_field = getModelName($id, $name, $field);
                if (false !== $model->where($condition)->delete()) {
                    $new = array();
                    $msg = '删除 ' . $name . ': ' . $mod_field . ' (编号：' . $id . ')';
                    if ('Action' != $name)
                        A('Action')->writeLog($msg, '删除', $name,$id, $old,$new);
                    $jumpUrl = $_REQUEST['jumpUrl'];
                    if(empty($jumpUrl))
                        $jumpUrl = Cookie::get ( '_currentUrl_' );
                    $this->assign ( 'jumpUrl', $jumpUrl );
                    $this->success('删除成功！');
                } else {
                    $this->error ('删除失败！');
                }
            } else {
                $this->error ( '非法操作' );
            }
        }
        $this->forward ();
    }

    public function clear() {
        //删除指定记录
        $name=$this->getActionName();
        $model = D ($name);
        if (! empty ( $model )) {
            if (false !== $model->where ( 'status=1' )->delete ()) {
                $this->assign ( "jumpUrl", $this->getReturnUrl () );
                $this->success ( L ( '_DELETE_SUCCESS_' ) );
            } else {
                $this->error ( L ( '_DELETE_FAIL_' ) );
            }
        }
        $this->forward ();
    }
    /**
     +----------------------------------------------------------
     * 默认禁用操作
     *
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    public function forbid() {
        $name=$this->getActionName();
        $model = D ($name);
        $pk = $model->getPk ();
        $id = $_REQUEST [$pk];
        $condition = array ($pk => array ('in', $id ) );
        $list=$model->forbid ( $condition );
        if ($list!==false) {
            //模式为3时，this->getReturnUrl()会返回错误，故不应在resume,forbid下使用。
            $this->assign ( "jumpUrl", $this->getReturnUrl () );
            $this->success ( '状态禁用成功' );
        } else {
            $this->error  (  '状态禁用失败！' );
        }
    }

    //默认改变状态值
    public function setFieldValue() {
        $name=$this->getActionName();
        $model = D ($name);
        $pk = $model->getPk ();
        $id = $_REQUEST [$pk];
        $newValue = empty($_REQUEST ['new'])? 0 : $_REQUEST ['new'];
        $field = empty($_REQUEST ['field'])? 'status' : $_REQUEST ['field'];
        $condition = array ($pk => array ('in', $id ) );
        $list=$model->setFieldValue ( $condition,$newValue,$field);
        if ($list!==false) {
            //模式为3时，this->getReturnUrl()会返回错误，故不应在resume,forbid下使用。
            $this->assign ( "jumpUrl", $this->getReturnUrl () );
            $this->success ( '新值改变成功' );
        } else {
            $this->error  (  '新值改变失败！' );
        }
    }

    public function checkPass() {
        $name=$this->getActionName();
        $model = D ($name);
        $pk = $model->getPk ();
        $id = $_GET [$pk];
        $condition = array ($pk => array ('in', $id ) );
        if (false !== $model->checkPass( $condition )) {
            $this->assign ( "jumpUrl", $this->getReturnUrl () );
            $this->success ( '状态批准成功！' );
        } else {
            $this->error  (  '状态批准失败！' );
        }
    }

  

    public function recycle() {
        $name=$this->getActionName();
        $model = D ($name);
        $pk = $model->getPk ();
        $id = $_GET [$pk];
        $condition = array ($pk => array ('in', $id ) );
        if (false !== $model->recycle ( $condition )) {

            $this->assign ( "jumpUrl", $this->getReturnUrl () );
            $this->success ( '状态还原成功！' );

        } else {
            $this->error   (  '状态还原失败！' );
        }
    }

    public function recycleBin() {
        $map = $this->_search ();
        $map ['status'] = - 1;
        $name=$this->getActionName();
        $model = D ($name);
        if (! empty ( $model )) {
            $this->_list ( $model, $map );
        }
        $this->display ();
    }

    /**
     +----------------------------------------------------------
     * 默认恢复操作
     *
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    function resume() {
        //恢复指定记录
        $name=$this->getActionName();
        $model = D ($name);
        $pk = $model->getPk ();
        $id = $_GET [$pk];
        $condition = array ($pk => array ('in', $id ) );
        if (false !== $model->resume ( $condition )) {
            $this->assign ( "jumpUrl", $this->getReturnUrl () );
            $this->success ( '状态恢复成功！' );
        } else {
            $this->error ( '状态恢复失败！' );
        }
    }


    function saveSort() {
        $seqNoList = $_POST ['seqNoList'];
        if (! empty ( $seqNoList )) {
            //更新数据对象
            $name=$this->getActionName();
            $model = D ($name);
            $col = explode ( ',', $seqNoList );
            //启动事务
            $model->startTrans ();
            foreach ( $col as $val ) {
                $val = explode ( ':', $val );
                $model->id = $val [0];
                $model->sort = $val [1];
                $result = $model->save ();
                if (! $result) {
                    break;
                }
            }
            //提交事务
            $model->commit ();
            if ($result!==false) {
                //采用普通方式跳转刷新页面
                $this->success ( '更新成功' );
            } else {
                $this->error ( $model->getError () );
            }
        }
    }

    /**
     * 返回多个房间，checkbox
     */
    public function getRoom(){
        $house_id = intval($_POST['house_id']);
        //$data = M('Room')->where('house_id ='.$house_id.' and status=1')->order('sort asc')->findAll();
        //查找当天可用房间
        $data = getAvailableRooms($house_id, '');
        $str = '';
        if(!data){
            return $str= "<span id='room'>没有房间</span>";
        }
        $str = " <span id='room'> 房间： ";
        foreach ($data as $value) {
            $str .= '<input type="checkbox" name="room_id[]" id="room_id" value="'.$value['room_id'].'">'.$value['room_no'];
        }
        echo $str.="</span>";
    }



    /**
     *处理上传图片，包括公寓及房型，文章等的图片（文章图片暂不做）
     * @param <type> $objId 公寓或房型ID
     * @param <type> $type type=0 公寓，1房型
     * @return <type>
     */
    public function process_photo($objId,$type=0) {
        //$_FILES = $files;
        $object = ($type ==0) ?'hotel':'house';
        import("@.ORG.UploadFile");
          //如果指定类型则删除原有的上传图片
       $cond=empty($_FILES['logo']['name'])?'':'attachfunc=2'; //如果定义了上传logo则删除原有的logo
       $old_attach = implode(',',$_POST['old_attach']);
       if (!empty($old_attach)) {
           $cond.=" or (attachfunc=1 and id not in ({$old_attach}))";
       }else {
           $cond.=" or attachfunc=1";
       }
       $cond = (substr($cond,0,4)==' or ')?substr($cond,4):$cond;
       $cond = $object."_id=".$objId." and (".$cond.")";
       $data = M('Attach')->where($cond)->select();
       //删除指定的文件
       if ($data) {
           foreach ($data as $key => $val) {
               unlink($val['path'].'thumb_'.$val['filename']);
               unlink($val['path'].$val['filename']);
           }
           M('Attach')->where($cond)->delete();
       }

        $upload = new UploadFile();
        $savePath = './Public/Uploads/'.$object.'/';
        if(!file_exists($savePath)) {
            mkdir($savePath,0777,true);
        }
        $upload->savePath =  $savePath;
        $upload->saveRule =  'uniqid';
        //$upload->saveRule =  '';//为空保持文件名不变，SEO友好或将来把产品名写入图片名称中TODO savename需要改为name+uninquId
        $upload->thumb   =  true;
        $upload->thumbMaxWidth = 100;
        $upload->thumbMaxHeight = 100;
        $upload->thumbPrefix = 'thumb_';
        if (!$upload->upload()) {
            $errormsg = $upload->getErrorMsg();
            if ($errormsg!='没有选择上传文件') {
                $this->errmsg .= "<br/>";
                $this->errmsg .=  $upload->getErrorMsg();//添加出错信息
            }
            return false;
        }
        $file_info = $upload->getUploadFileInfo();
        $islogo = empty($_FILES['logo']['name'])?0:1;
        //import("@.ORG.Image");
        foreach ($file_info as $key => $value) {
            //Image::water($savePath.$value['savename'], './Public/Images/home/ok_water.png');//透明度80% 水印功能暂不做
            $data = array(
                    $object.'_id'=>$objId,
                    'filename'=>$value['savename'],
                    'attachfunc'=>1,
                    'path'=>$value['savepath'],
                    'url'=>$value['savepath'].$value['savename'],
                    'size'=>intval($value['size']/1024),
                    'attachext'=>$value['extension'],
                    'create_time'=>time(),
                    'status'=>1,
            );
            if ($key==0 && $islogo==1) {
                $data['attachfunc']=2;
            }
            $insid = M('Attach')->add($data);
        }
    }

    public function success($message,$ajax=false,$waitSecond = 0.1){
        $this->assign('waitSecond',$waitSecond);
        parent::success($message, $ajax);

    }
    

    public function getAllMember() {
        $q = strtolower($_GET["term"]);
        if (!$q) return;
        $data = M('Member')->where('status = 1')->field('id,account,name')->order("create_time desc")->findAll();
        $allresult = array();
        foreach($data as $key=>$value) {
            $allresult[ $value['id'] ] = $value['account'].'('.$value['name'].')';
        }
        $result = array();
        foreach ($allresult as $value=>$key) {
            if (strpos(strtolower($key), $q) !== false) {
                array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
            }
            if (count($result) > 11)
                break;
        }
        echo array_to_json($result);
        //$this->ajaxReturn($result,'',1);
    }



    //获得县市
    public function getCountry()
    {
        $city_code = intval($_POST["city_code"]);
        $str = "";
        foreach(M("Country")->where("city_code={$city_code}")->select() as $value){
            $str .= "<option value='{$value[coun_code]}'>{$value['coun_name']}</option>";
        }
        echo $str;
    }
    public function getCity()
    {
        $province_code = intval($_POST["prov_code"]);
        $str = "";
        foreach(M("City")->where("prov_code={$province_code}")->select() as $value){
            $str .= "<option value='{$value[city_code]}'>{$value['city_name']}</option>";
        }
        echo $str;
    }

     
     /**
     * 通过查询，自动提示供应商，并返回相应搜索结果，用于自动提示
     * @return <json> filter_product data
     */
    public function filter_supplier() {
        if(empty ($_POST['q'])){
            return false;
            exit;
        }
        $q = isset($_POST['q']) ? strval($_POST['q']) : '';

        //按条码或拼音查询（tm,helpword）
        $mod = 'name';
        $where = array(
            $mod => array('like','%'.$q.'%')
        );
        $map['_complex'] = $where;
        $map['status'] = 1;
        $rs = M('Supplier')->where($map)->field('id,name')->limit(10)->findAll();
        echo json_encode($rs);
    }

     /**
     * 通过查询，自动提示产品，返回相应产品结果
     * @return <json> filter_product data
     */
    public function filter_product() {
        if(empty ($_POST['q'])){
            return false;
            exit;
        }
        $q = isset($_POST['q']) ? strval($_POST['q']) : '';

        //按条码或拼音查询（tm,helpword）
        $mod = isset($_GET['type']) ? strval($_GET['type']) : 'cas';
        $where = array(
            $mod => array('like','%'.$q.'%')
        );
        $map['_complex'] = $where;
        $map['status'] = 1;
        $rs = M('Product')->where($map)->field('id,name,ename,cas')->limit(30)->findAll();
        echo json_encode($rs);
    }

     /**
     * 通过ajax ，根据产品ID(单个)返回产品详情，并输出为tr格式
     * 
     */
    public function getProductDetail(){
        $product_id= $_POST['product_id'];
        //交易类型：销售，入库，退货？。。。。。默认为入库
        //TODO 暂取销售，sale=order
        $trans_type = isset($_POST['trans_type']) ? $_POST['trans_type'] : 'sale';
        $data = M('Product')->where('id ='.intval($product_id) )->find();

        if (count($data) > 0) {

            $product_str = "<tr class='tLeft' id='product_td'>";
            $product_str .="<td><input type='hidden' name='product_id[]' value='" . $product_id . "'/> <p class='span3'>" . $data['name'] .$data['ename'].':'.$data['cas']. '</p></td>';
            
      
            //price 不同
            switch ($trans_type){
                case 'sale':{
                $product_str .="<td><input type='text' class='input-mini' name='price[]' value=''/></td>";    //单价
                }
                    break;
            }
            $count_asksup = M('Ask_supplier_detail')->where('product_id ='.$product_id)->count('id');

            $product_str .="<td><input type='text' class='input-mini' name='number[]' class ='small'/></td>";    //数量
            $product_str .='<td class="span1"> <input type="hidden" name="unit_id[]" value="1">KG</td>';    //单位 默认KG
            $product_str .='<td class="span1"> <input type="text" class="span1" name="logifee[]"></td>';
            $product_str .="<td>".modList('Specification',-1,'span3','specification[]')."</td>";    //规格
            $product_str .="<td><input type='text' class='input-small' name='delivery_date[]' onClick='WdatePicker()' /></td>";   //要求交货期
            $product_str .="<td><select name='priority[]' class='span2'><option value='0'>普通</option><option value='1'>现货</option><option value='2'>急单</option>  </select></td>";        //priority
            $product_str .='<td><input type="text" class="input-small" name="dcost[]" ></td>';        //成本
            $product_str .='<td><input type="text" class="input-small" name="dto_first_pay[]" ></td>';        //预付款
            //$product_str .='<td><input type="text" class="input-small" name="dto_remain_pay[]" ></td>';        //余款,系统自动计算
            $product_str .="<td><input type='hidden' name='dstatus[]' value='-1'>待审批</td>";    //状态
            $product_str .="<td><a href='#' onClick='window.open(\"".__APP__."/Product/asksup/id/".$product_id ."\",\"\",\"height=600,width=700,scrollbars=yes,status =yes\")'>询价(".$count_asksup.")</a></td>";   //相关询价

            $data['product_detail'] = $product_str . " <td class='span1'><img src='".__APP__."/Public/Images/publish_x.png' alt='删除' onclick='removerow(this);'/></td></tr>";
            $this->ajaxReturn($data, '', 1);

        }else{
            $this->ajaxReturn(null, '提交的产品有问题！', 0);
        }
    }

    /**
     * 通过ajax ，根据order_detail_id返回order_detail，并输出为tr格式
     * 
     */
    public function getOrderDetail(){
        $order_detail_id= $_POST['order_detail_id'];
        //交易类型：销售，入库，退货？。。。。。默认为入库
        //TODO 暂取销售，sale=order
        $trans_type = isset($_POST['trans_type']) ? $_POST['trans_type'] : 'sale';
        $data = M('Order_detail')->where('id ='.intval($order_detail_id) )->find();
        if (count($data) > 0) {

            $product_str = "<tr class='tLeft' id='product_td'> <input type='hidden' name='order_detail_id[]' value='".$order_detail_id."'>";
            $product_str .="<td><input type='hidden' name='product_id[]' value='" . $data['product_id'] . "'/> <p class='span3'>" . $data['mano'] .'</p></td>';
            $product_str .="<td colspan> <p class='span3'>" . getPfullName($data['product_id']) .'</p></td>';
            $product_str .="<td colspan> <p class='span3'>" . getCas($data['product_id']) .'</p></td>';
            $product_str .="<td colspan> <p class='span3'>" . getModelName($data['specification'],'Specification') .'</p></td>';
            $product_str .="<td><input type='hidden' name='price[]' value='" . $data['price'] . "'/> <input type='text' name='number[]' class='span2' value='" . $data['number'] . "'/>库存：".getStock($data['product_id'],$data['specification'])." </td>";
            $product_str .="<td>KG</td>";
            $product_str .="<td><input type='hidden' name='total[]' value='" . $data['total'] . "'/>" . $data['total'] . " </td>";
            $product_str .="<td><input type='hidden' name='logifee[]' value='" . $data['logifee'] . "'/>" . $data['logifee'] . " </td>";
            $product_str .="<td><input type='hidden' name='sum_total[]' value='" . $data['should_pay'] . "'/>" . $data['should_pay'] . " </td>";
            

            $data['product_detail'] = $product_str . " <td class='span1'><img src='".__APP__."/Public/Images/publish_x.png' alt='删除' onclick='removerow(this);'/></td></tr>";
            $this->ajaxReturn($data, '', 1);

        }else{
            $this->ajaxReturn(null, '提交的产品有问题！', 0);
        }
    }


}
?>
